<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
  <meta name="generator" content=
  "HTML Tidy for Linux/x86 (vers 1 September 2005), see www.w3.org">

  <title>capacity</title>
  <link href="../cppreference.css" rel="stylesheet" type="text/css">
</head>

<body>
<table>
  <tr>
  <td>
  <div class="body-content">

  <div class="header-box">
    <a href="../index.html">cppreference.com</a> &gt; <a href=
    "index.html">C++ Vectors</a> &gt; <a href=
    "capacity.html">capacity</a>
  </div>

  <div class="name-format">
    capacity
  </div>

  <div class="syntax-name-format">
    Syntax:
  </div>
  <pre class="syntax-box">
  #include &lt;vector&gt;
  <strong>size_type</strong> capacity() const;
</pre>

  <p>The capacity() function returns the number of elements that the
  vector can hold before it will need to allocate more space.</p>

  <p>For example, the following code uses two different methods to set
  the capacity of two vectors. One method passes an argument to the
  constructor that suggests an initial size, the other method calls the
  reserve function to achieve a similar goal:</p>
  <pre class="example-code">
 vector&lt;int&gt; v1(10);
 cout &lt;&lt; &quot;The capacity of v1 is &quot; &lt;&lt; v1.capacity() &lt;&lt; endl;
 vector&lt;int&gt; v2;
 v2.reserve(20);
 cout &lt;&lt; &quot;The capacity of v2 is &quot; &lt;&lt; v2.capacity() &lt;&lt; endl;         
</pre>

  <p>When run, the above code produces the following output:</p>
  <pre class="example-code">
 The capacity of v1 is 10
 The capacity of v2 is 20               
</pre>

  <p>C++ containers are designed to grow in size dynamically. This
  frees the programmer from having to worry about storing an arbitrary
  number of elements in a container. However, sometimes the programmer
  can improve the performance of her program by giving hints to the
  compiler about the size of the containers that the program will use.
  These hints come in the form of the <a href=
  "reserve.html">reserve</a>() function and the constructor used in the
  above example, which tell the compiler how large the container is
  expected to get.</p>

  <p>The capacity() function runs in <a href=
  "../complexity.html">constant time</a>.</p>

  <div class="related-name-format">
    Related topics:
  </div>

  <div class="related-content">
    <a href="reserve.html">reserve</a><br>
    <a href="resize.html">resize</a><br>
    <a href="size.html">size</a>
  </div>
  </div>
  </td>
  


  </tr>
  </table>
</body></html>
